<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="单据名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入单据编号" clearable style="width: 240px"
                      @keyup.enter=""/>
          </el-form-item>
          <el-form-item label="供应商" prop="partnerId">
            <el-input v-model="partnerName" placeholder="请选择供应商" style="width: 240px"
                      @keyup.enter="">
              <template #append>
                <el-button icon="Search" @click="partnerDialogHandle"/>
              </template>
              <template #prepend>
                <el-button icon="Delete" @click="partnerDialogDelete"/>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="更新时间" style="width: 290px">
            <el-date-picker
              v-model="dateRangeUpdateTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['demo:demo2:add']">
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain :disabled="multiple" icon="Delete" @click="handleDelete" v-hasPermi="['demo:demo2:remove']">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['demo:demo2:export']">
              导出
            </el-button>
          </el-col>
        </el-row>
      </template>

      <el-table :data="orderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center"/>
        <el-table-column label="单据名称" align="center" prop="name" />
        <el-table-column label="供应商" align="center" prop="partnerId">
          <template #default="scope">
            {{ getPartnerChildData(scope.row.partnerId) }}
          </template>
        </el-table-column>
        <el-table-column label="单据状态" align="center" prop="status">
          <template #default="scope">
            <el-button :type="getType(scope.row.status)" @click="examine(scope.row)">
              <dict-tag :options="wms_order_status" :value="scope.row.status"/>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark"/>
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" >
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleChange(scope.row, false)"/>
            </el-tooltip>
            <el-tooltip content="复制" placement="top">
              <el-button link type="primary" icon="DocumentCopy" @click="handleChange(scope.row, true)"/>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"  v-hasPermi="['wms:order:remove']"/>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改跟物品有关的订单对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible"
               style="width: 90%; height: 90%"
               append-to-body
               :close-on-click-modal='false'
               :close-on-press-escape="false"
               :show-close="false"
    >

      <el-form :rules="rules" :model="form" ref="orderFormRef" :inline="true" label-width="80px" >
        <el-form-item label="单据名称" prop="name" >
          <el-input v-model="form.name" placeholder="请输入单据编号" clearable style="width: 240px"/>
        </el-form-item>
        <el-form-item label="供应商" prop="partnerId">
          <el-input v-model="partnerName" placeholder="请选择供应商" style="width: 240px"
                    @keyup.enter="">
            <template #append>
              <el-button icon="Search" @click="partnerDialogHandle"/>
            </template>
            <template #prepend>
              <el-button icon="Delete" @click="partnerDialogDelete"/>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="单据状态" prop="status">
          <DictSelect :dictType="'wms_order_status'" v-model:dictValue="form.status" placeholder="请选择单据状态" />
        </el-form-item>
        <el-form-item label="备注" prop="remark" style="width: 100%">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" style="width: 90%" />
        </el-form-item>
      </el-form>

      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" style="margin-bottom: 15px; display: flex">
        <el-col :span="1.5">
          <ProductSearch :searchType="2" :params="{isStock:1}" @ok="lineAdd" title="服务新增"/>
        </el-col>
      </el-form>

      <el-table :data="orderLineList">
        <el-table-column type="selection" width="180" align="center"/>
        <el-table-column label="产品ID" align="center" prop="productId" />
        <el-table-column label="产品名称" align="center" prop="name" >
          <template #default="scope">
            <el-input :model-value="getNameChildData(scope.row.productId)"/>
          </template>
        </el-table-column>
        <el-table-column label="批次号" align="center" prop="batchCode">
          <template #default="scope">
            <el-input v-model="scope.row.batchCode" placeholder="请输入批次号"/>
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" prop="measureUnit">
        <template #default="scope">
          <el-input v-model="scope.row.measureUnit" placeholder="请输入单位"/>
        </template>
        </el-table-column>
        <el-table-column label="价格" width="120" align="center" prop="price"/>
        <el-table-column label="入库数量" align="center" prop="quantity" >
          <template #default="scope">
            <el-input @input="computedMoney(scope.row)"  v-model="scope.row.quantity" placeholder="请输入入库数量"
                      oninput="value=value.replace(/\D/g, '')"/>
          </template>
        </el-table-column>
        <el-table-column label="优惠金额" align="center" prop="discountMoney" >
          <template #default="scope">
            <el-input @input="computedMoney(scope.row)" v-model="scope.row.discountMoney" placeholder="请输入优惠金额"
                      oninput="value=value.replace(/\D/g, '')"/>
          </template>
        </el-table-column>
        <el-table-column label="总金额" align="center" prop="total_money" >
          <template #default="scope">
            <el-input v-model="scope.row.totalMoney" placeholder="请输入总金额" readonly/>
          </template>
        </el-table-column>
        <el-table-column label="应收金额" align="center" prop="costMoney">
          <template #default="scope">
            <el-input v-model="scope.row.costMoney" placeholder="应收金额" readonly/>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer" style="position: absolute; right:20px; bottom:15px;">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--  供应商  -->
    <el-dialog v-model="partnerDialog.visible" style="width: auto">
      <el-table v-loading="loading" :data="partnerList" @row-click="partnerSelect">
        <el-table-column label="上级" align="center" prop="parentId" />
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="编码" align="center" prop="code" />
        <el-table-column label="性别" align="center" prop="sex">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="mobile" />
        <el-table-column label="是否启用" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="固定电话" align="center" prop="telephone" />
        <el-table-column label="邮箱" align="center" prop="email" />
        <el-table-column label="是否客户" align="center" prop="isCustomer">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.isCustomer"/>
          </template>
        </el-table-column>
        <el-table-column label="是否供应商" align="center" prop="isSupplier">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.isSupplier"/>
          </template>
        </el-table-column>
        <el-table-column label="图片" align="center" prop="picture" />
        <el-table-column label="备注" align="center" prop="remark" />
      </el-table>
    </el-dialog>
  </div>
</template>
<!-- 采购订单 typeId === 22 -->
<script setup name="OrderPurchase" lang="ts">
import {addOrder, delOrder, getOrder, listOrder, updateOrder} from '@/api/wms/order';
import {listPartner} from '@/api/hrp/partner';
import {OrderForm, OrderLineQuery, OrderQuery, OrderVO} from '@/api/wms/order/types';
import DictSelect from "@/views/system/dict/select.vue";
import {PartnerVO} from "@/api/hrp/partner/types";
import {listOrderLine} from "@/api/wms/order";
import {OrderLineVO} from "@/api/wms/order/types";
import {onMounted} from "vue";
import {ProductVO} from "@/api/wms/product/types";
import ProductSearch from "@/views/wms/product/search.vue";
import {listProduct} from "@/api/wms/product";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wms_order_status, sys_user_sex, sys_yes_no } = toRefs<any>(proxy?.useDict('wms_order_status', 'sys_user_sex', 'sys_yes_no'));
const orderList = ref<OrderVO[]>([]);
const orderLineList = ref<OrderLineVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const partnerTotal = ref(0);
const dateRangeUpdateTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const orderFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const partnerDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: OrderForm = {
  id: undefined,
  name: undefined,
  typeId: 22,
  partnerId: undefined,
  selfWhId: undefined,
  otherWhId: undefined,
  status: undefined,
  sourceId: undefined,
  manufacturerId: undefined,
  applicantId: undefined,
  execId: undefined,
  remark: undefined,
  line: undefined
}
const data = reactive<PageData<OrderForm, OrderQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    name: undefined,
    typeId: 22,
    partnerId: undefined,
    selfWhId: undefined,
    status: undefined,
    params: {
      updateTime: undefined,
    }
  },
  rules: {
    name: [
      { required: true, message: "单据名称不能为空", trigger: "blur" }
    ],
    typeId: [
      { required: true, message: "单据类型不能为空", trigger: "blur" }
    ],
    partnerId: [
      { required: true, message: "客户不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "单据状态不能为空", trigger: "blur" }
    ],

  }
});

const { queryParams, form, rules } = toRefs(data);

const copy = reactive({is: false})

onMounted(() => {
  // typeList();
  nameList()
  partnerGetList()
  getList()
});

/** 查询跟物品有关的订单列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeUpdateTime.value, 'UpdateTime');
  const res = await listOrder(queryParams.value);
  orderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  dateRangeUpdateTime.value = ['', ''];
  partnerDialogDelete()
  handleQuery();
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}
/** 多选框选中数据 */
const handleSelectionChange = (selection: PartnerVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 删除按钮操作 */
const handleDelete = async (row?: OrderVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除跟物品有关的订单编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delOrder(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}
/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  orderFormRef.value?.resetFields();
  partnerDialogDelete()
  orderLineList.value = []
}
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "新增";
}
/** 修改按钮操作 */
function handleChange(row: OrderVO, isCopy: boolean){
  reset();
  getOrderById(row.id)
  getLineList(row.id);
  dialog.visible = true;
  dialog.title = "修改";
  copy.is = isCopy
}
async function getOrderById(id: any){
  const res = await getOrder(id)
  partnerName.value = getPartnerChildData(res.data.partnerId)
  form.value = {...res.data}
}
/** 导出按钮操作 */
function handleExport() {
  proxy?.download('wms/order/export', {
    ...queryParams
  }, `order_${new Date().getTime()}.xlsx`)
}
/** 提交按钮 */
const submitForm = () => {
  orderFormRef.value?.validate(async (valid1: boolean) => {
    if (toRaw(orderLineList.value).length === 0){
      proxy?.$modal.msgWarning('请添加至少一项产品')
      return
    }
    if (valid1) {
      buttonLoading.value = true;
      form.value.line = orderLineList.value
      if (form.value.id && !copy.is) {
        await updateOrder(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        if (form.value.id) {
          form.value.id = undefined
          form.value.line.forEach(item=>{item.id = undefined;item.lineId = undefined;})
        }
        await addOrder(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      partnerDialogDelete()
      dialog.visible = false;
      await getList();
    }
    copy.is = false
  });
}
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  dialog.title = ''
}

/** 查询供应商列表 */
const partnerList = ref<PartnerVO[]>([]);
async function partnerGetList(){
  loading.value = true;
  queryParams.value.params = {};
  await proxy?.addDateRange(queryParams.value, dateRangeUpdateTime.value, 'UpdateTime');
  const res = await listPartner();
  partnerList.value = res.rows;
  partnerTotal.value = res.total
  loading.value = false;
}
/** 显示对应 供应商name */
const getPartnerChildData = (id: string | number) => {
  const childItem = partnerList.value.find(item => item.id === id);
  return childItem ? childItem.name : 'No related data';
}

/** 显示对应 产品名称 */
let productNameList = ref()
const nameList = async ()=>{
  const ref = toRaw( await listProduct() )
  productNameList.value = ref.rows
}
const getNameChildData = (id: string | number) => {
  const childItem = productNameList.value.find((item: { id: string | number; }) => item.id === id);
  return childItem ? childItem.name : 'No related data';
}
/** 状态列颜色 */
function getType(row: any){
  if(row == 0){
    return 'success'
  }else if(row == 1){
    return 'info'
  }
}
/** 审核 反审核 */
async function examine(row: OrderVO){
  const _ids = row?.id;
  await proxy?.$modal.confirm('是否更改ID项'+ _ids +'审核状态？').finally(() => loading.value = false);
  form.value = {...row}
  form.value.status = row?.status === '0' ? '1' : '0'
  await updateOrder(form.value)
  proxy?.$modal.msgSuccess("修改成功");
  await getList();
}

/** 供应商输入框 */
const partnerName = ref<any>()
function partnerSelect(row: any){
  partnerName.value = row.name
  if (dialog.title){
    form.value.partnerId = row.id
  }else {
    queryParams.value.partnerId = row.id
  }
  partnerDialog.visible = false
}
function partnerDialogHandle(){
  partnerDialog.visible = true
}
function partnerDialogDelete(){
  partnerName.value = ''
  form.value.partnerId = ''
  queryParams.value.partnerId = ''
}


function computedMoney(item: any){
  item.totalMoney = item.price * item.quantity
  item.costMoney = item.totalMoney - item.discountMoney
}

/** 新增一行按钮操作 */
async function lineAdd(vo:ProductVO[]) {
  let line: OrderLineVO = {};
  vo.forEach((v)=>{
    line.productId = v.id;
    line.name = v.name;
    line.price = v.price;
    line.measureUnit = v.measureUnit;
    line.quantity = 1;
    line.totalMoney = v.price;
    line.discountMoney = 0;
    line.costMoney = line.totalMoney - line.discountMoney;
    orderLineList.value.push(line)
  });
}
/** 查询测试子列表 */
const queryLineParams = reactive<OrderLineQuery>({
  pageNum: 1,
  pageSize: 10,
  id: undefined
})
async function getLineList(row: any) {
  loading.value = true;
  queryLineParams.id = row;
  await listOrderLine(queryLineParams).then(res => {
    orderLineList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
  }
</script>
